﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using DevExpress.XtraGrid.Views.Grid;
using System.Drawing;
using DevExpress.XtraEditors;
using System.Reflection;
using System.IO;
using System.Xml;
using DevExpress.Utils;
using DevExpress.XtraGrid.Columns;
using System.Windows.Forms;
using DevExpress.XtraGrid.Menu;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Mask;
using DevExpress.XtraEditors.Controls;

namespace ElingAppSystemCtrls
{
    public partial class EASGridControl : DevExpress.XtraGrid.GridControl
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private string FilePath = "";
        /// <summary>
        /// 构造函数
        /// </summary>
        public EASGridControl()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 结束初始化
        /// </summary>
        protected override void OnEndInit()
        {
            base.OnEndInit();
            if (!this.DesignMode)
            {
                 if (this.MainView is DevExpress.XtraGrid.Views.Layout.LayoutView)
                 {
                     return;
                 }


                 DevExpress.XtraGrid.Views.Grid.GridView gdview = (DevExpress.XtraGrid.Views.Grid.GridView)this.MainView;

                if (gdview != null)
                {

                    //隐藏最上面的GroupPanel
                    gdview.OptionsView.ShowGroupPanel = false;
                    //设置显示横向滚动条
                    gdview.OptionsView.ColumnAutoWidth = false;
                    gdview.OptionsView.ShowFooter = true;

                    gdview.OptionsFilter.AllowFilterEditor = false;
                    gdview.OptionsCustomization.AllowFilter = false;
                    gdview.OptionsCustomization.AllowQuickHideColumns = false;

                    gdview.OptionsMenu.EnableFooterMenu = false;
                    gdview.OptionsMenu.EnableGroupPanelMenu = false;

                    
                    //gdview.OptionsLayout.StoreAllOptions = false;
                    //gdview.OptionsLayout.Columns.AddNewColumns = false;
                    //gdview.OptionsLayout.Columns.RemoveOldColumns = false;
                    //gdview.OptionsLayout.Columns.StoreAppearance = true;
                    //gdview.OptionsLayout.Columns.StoreLayout = true;
                    //gdview.OptionsLayout.Columns.StoreAllOptions = false;


                    

                }
                string lastVerson = this.LastGridLayoutDate;
                string filepathBase = AppDomain.CurrentDomain.BaseDirectory + "ClientConfig" + "\\";

                DateTime? codeDate = null;
                DateTime? configDate = null;
                if (!string.IsNullOrEmpty(lastVerson))
                {
                    codeDate = DateTime.Parse(lastVerson);
                    gdview.OptionsLayout.LayoutVersion = codeDate.Value.ToString("yyyy-MM-dd");
                }

                Control ownForm = this.FindForm();
                string parentName = "";
                if (ownForm != null)
                {
                    parentName = ownForm.Name;
                }
                else
                {
                    parentName = this.Parent.Name;
                }
                gdview.OptionsLayout.StoreAllOptions = false;
                gdview.OptionsLayout.StoreAppearance = false;
                gdview.OptionsLayout.StoreVisualOptions = false;
                gdview.OptionsLayout.StoreDataSettings = false;

                gdview.OptionsLayout.Columns.StoreAllOptions = false;
                gdview.OptionsLayout.Columns.StoreAppearance = false;
                gdview.OptionsLayout.Columns.StoreLayout = true;
                gdview.OptionsLayout.Columns.RemoveOldColumns = false;
                gdview.OptionsLayout.Columns.AddNewColumns = false;

                FilePath = filepathBase + parentName + "_" + this.Name + "_" + gdview.Name + ".xml";
                if (File.Exists(FilePath))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(FilePath);
                    XmlNode xmlNode = xmlDoc.SelectSingleNode("//property[@name='#LayoutVersion']");
                    DateTime tmpDate;
                    if (DateTime.TryParse(xmlNode.InnerXml, out tmpDate))
                    {
                        configDate = tmpDate;
                    }

                    if (codeDate != null && configDate != null)
                    {
                        if (codeDate > configDate)
                        {
                            File.Delete(FilePath);
                        }
                        else
                        {


                            gdview.RestoreLayoutFromXml(FilePath, gdview.OptionsLayout);
                        }

                    }
                    else
                    {
                        File.Delete(FilePath);
                    }
                }

                if (File.Exists(FilePath))
                {

                    gdview.RestoreLayoutFromXml(FilePath, gdview.OptionsLayout);
                }
                if (!string.IsNullOrEmpty(this.LastGridLayoutDate))
                {
                    gdview.ColumnPositionChanged += new EventHandler(gdview_ColumnPositionChanged);
                    gdview.ColumnWidthChanged += new DevExpress.XtraGrid.Views.Base.ColumnEventHandler(gdview_ColumnWidthChanged);
                }
                gdview.RowStyle += new RowStyleEventHandler(gdview_RowStyle);
                gdview.CustomColumnDisplayText += new DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventHandler(gdview_CustomColumnDisplayText);
                gdview.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(gdview_CustomDrawCell);
                gdview.PopupMenuShowing += new PopupMenuShowingEventHandler(gdview_PopupMenuShowing);
                gdview.ShownEditor += new EventHandler(gdview_ShownEditor);
                foreach(GridColumn gridCol in gdview.Columns)
                {
                    if (gridCol.AppearanceHeader.TextOptions.HAlignment == HorzAlignment.Default)
                    {
                        gridCol.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
                    }
                     RepositoryItem repositoryItem = gridCol.ColumnEdit;
                     if (repositoryItem != null)
                     {
                         if (repositoryItem is RepositoryItemCheckEdit)
                         {
                             RepositoryItemCheckEdit checkItem = repositoryItem as RepositoryItemCheckEdit;
                             checkItem.AutoHeight = false;
                             checkItem.NullStyle = DevExpress.XtraEditors.Controls.StyleIndeterminate.Unchecked;
                             if (gridCol.FieldName == "pics" || gridCol.FieldName == "ga_pics")
                             {
                                 checkItem.QueryCheckStateByValue += new QueryCheckStateByValueEventHandler(MoreThanZero_QueryCheckStateByValue);
                             }
                             else
                             {
                                 checkItem.QueryCheckStateByValue += new QueryCheckStateByValueEventHandler(checkItem_QueryCheckStateByValue);
                             }
                         }
                         else
                         {
                             if (repositoryItem is RepositoryItemTextEdit)
                             {
                                 RepositoryItemTextEdit textEditItem = repositoryItem as RepositoryItemTextEdit;
                                 if (textEditItem.Mask.MaskType == MaskType.Numeric)
                                 {
                                     textEditItem.Spin += new DevExpress.XtraEditors.Controls.SpinEventHandler(textEditItem_Spin);
                                 }
                             }
                         }
                     }
                }
                
            }
        }
        /// <summary>
        /// 显示修改控件事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_ShownEditor(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            if (view.FocusedColumn.FieldName == "FAmount" || view.FocusedColumn.FieldName == "FDate" || view.FocusedColumn.FieldName == "FTaxRate")
            {
                view.ActiveEditor.ImeMode = ImeMode.Disable;
            }
        }

        /// <summary>
        /// 防止鼠标滚轮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textEditItem_Spin(object sender, DevExpress.XtraEditors.Controls.SpinEventArgs e)
        {
            e.Handled = true;
        }
        /// <summary>
        /// 大于0的选择框选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MoreThanZero_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
        {
            if (e.Value != null)
            {
                decimal d = 0;
                if (decimal.TryParse(e.Value.ToString(), out d))
                {
                    if (d > 0)
                    {
                        e.CheckState = CheckState.Checked;
                    }
                    else
                    {
                        e.CheckState = CheckState.Unchecked;
                    }
                }
            }
            e.Handled = true;
        }

        /// <summary>
        /// 选择框选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkItem_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
        {
            if (e.Value != null)
            {
                string val = e.Value.ToString();
                switch (val)
                {
                    case "True":
                        e.CheckState = CheckState.Checked;
                        break;
                    case "False":
                        e.CheckState = CheckState.Unchecked;
                        break;
                    case "Yes":
                        goto case "True";
                    case "No":
                        goto case "False";
                    case "1":
                        goto case "True";
                    case "0":
                        goto case "False";
                    case "Y":
                        goto case "True";
                    case "N":
                        goto case "False";

                    default:
                        e.CheckState = CheckState.Unchecked;
                        break;
                }
            }
            else
            {
                e.CheckState = CheckState.Unchecked;
            }
            e.Handled = true;
        }
        
        /// <summary>
        /// 绘制单元格的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "rent_sale")
            {
                if (e.CellValue != null)
                {
                    if (e.CellValue.ToString() == "0")
                    {
                        e.Appearance.ForeColor = Color.Red;
                    }
                }
            }
        }
        /// <summary>
        /// 定义列显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "pics")
            {
                if (e.Value != null)
                {
                    decimal d = 0;
                    if (decimal.TryParse(e.Value.ToString(), out d))
                    {
                        if (d > 0)
                        {
                            e.DisplayText = "√";
                        }
                        else
                        {
                            e.DisplayText = "";
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 表格列宽改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_ColumnWidthChanged(object sender, DevExpress.XtraGrid.Views.Base.ColumnEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView gdview = (DevExpress.XtraGrid.Views.Grid.GridView)e.Column.View;
            string filepathBase = AppDomain.CurrentDomain.BaseDirectory + "ClientConfig" + "\\";
            if (!Directory.Exists(filepathBase))
            {
                Directory.CreateDirectory(filepathBase);

            }

            //filepath += this.Parent.Name + "_" + this.Name + "_" + gdview.Name + ".xml";
            gdview.SaveLayoutToXml(FilePath, gdview.OptionsLayout);
        }
        /// <summary>
        /// 表格列位置改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_ColumnPositionChanged(object sender, EventArgs e)
        {
            GridColumn column = (GridColumn)sender;
            DevExpress.XtraGrid.Views.Grid.GridView gdview = (DevExpress.XtraGrid.Views.Grid.GridView)column.View;
            string filepathBase = AppDomain.CurrentDomain.BaseDirectory + "ClientConfig" + "\\";
            if (!Directory.Exists(filepathBase))
            {
                Directory.CreateDirectory(filepathBase);

            }
            gdview.OptionsLayout.StoreAllOptions = false;
            gdview.OptionsLayout.StoreAppearance = false;
            gdview.OptionsLayout.StoreVisualOptions = false;
            gdview.OptionsLayout.StoreDataSettings = false;

            gdview.OptionsLayout.Columns.StoreAllOptions = false;
            gdview.OptionsLayout.Columns.StoreAppearance = false;
            gdview.OptionsLayout.Columns.StoreLayout = true;
            gdview.OptionsLayout.Columns.RemoveOldColumns = false;
            gdview.OptionsLayout.Columns.AddNewColumns = false;
            //filepath += this.Parent.Name + "_" + this.Name + "_" + gdview.Name + ".xml";
            gdview.SaveLayoutToXml(FilePath, gdview.OptionsLayout);
        }
        /// <summary>
        /// 表格行样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle % 2 == 0)
            {
                e.Appearance.BackColor = Color.FromArgb(240, 248, 255);
            }
            DevExpress.XtraGrid.Views.Grid.GridView gdview = (DevExpress.XtraGrid.Views.Grid.GridView)this.MainView;
            object row = gdview.GetRowCellValue(e.RowHandle, "rent_sale_wake");
            if (row != null)
            {
                if (row.ToString() != "0")
                {
                    e.Appearance.ForeColor = Color.Gray;
                }
            }
            row = gdview.GetRowCellValue(e.RowHandle, "imp_cnt");
            if (row != null)
            {
                if (row.ToString() != "0")
                {
                    e.Appearance.ForeColor = Color.Red;
                }
            }
        }
        #region 表格右键相关
        /// <summary>
        /// 表格右键弹出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            GridView gdview = (GridView)sender;
            if (e.MenuType == GridMenuType.Column)
            {

                //// Customize
                //DXMenuItem miCustomize = GetItemByStringId(e.Menu, GridStringId.MenuColumnColumnCustomization);
                //if (miCustomize != null)
                //{
                //    miCustomize.Visible = false;
                //}

                List<DXMenuItem> visibleMenuList = new List<DXMenuItem>()
                {
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnGroup),
                    GetItemByStringId(e.Menu, GridStringId.MenuGroupPanelShow),
                    GetItemByStringId(e.Menu, GridStringId.MenuGroupPanelHide),
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnRemoveColumn),
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnColumnCustomization),
                    GetItemByStringId(e.Menu, GridStringId.MenuColumnFilterMode)
                };
                foreach (DXMenuItem dxItem in visibleMenuList)
                {
                    if (dxItem != null)
                    {
                        dxItem.Visible = false;
                    }
                }

                GridViewColumnMenu menu = e.Menu as GridViewColumnMenu;
                if (menu.Column != null)
                {
                    //添加菜单 
                    menu.Items.Add(CreateGridCheckItem("冻结列", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.Left,
                      null));
                }
               
            }
        }
        /// <summary>
        /// 获取右键菜单资源
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private DXMenuItem GetItemByStringId(DXPopupMenu menu, GridStringId id)
        {
            foreach (DXMenuItem item in menu.Items)

                if (item.Caption == GridLocalizer.Active.GetLocalizedString(id))

                    return item;

            return null;
        }

        /// <summary>
        /// 创建右键菜单
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="column"></param>
        /// <param name="style"></param>
        /// <param name="image"></param>
        /// <returns></returns>
        private DXMenuCheckItem CreateGridCheckItem(string caption, GridColumn column, DevExpress.XtraGrid.Columns.FixedStyle style, Image image)
        {
            DXMenuCheckItem item = new DXMenuCheckItem(caption, column.Fixed == style, image, new EventHandler(OnEASGridFixedClick));
            item.Tag = new EASGridMenuInfo(column, style, item.Checked);
            item.BeginGroup = true;
            return item;
        }
        /// <summary>
        /// 点击冻结列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnEASGridFixedClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            EASGridControl gridControl = this;
            GridView gdview = (GridView)this.MainView;
            gridControl.Update();
            EASGridMenuInfo info = item.Tag as EASGridMenuInfo;
            if (info == null)
            {
                return;
            }
            if (!info.Checked)
            {
                for (int i = 0; i < gdview.VisibleColumns.Count; i++)
                {
                    if (gdview.VisibleColumns[i].ToString().ToLower().Trim() == info.Column.Caption.ToLower().Trim())
                    {


                        ApplayGridFix(gdview.VisibleColumns[i].ToString(), DevExpress.XtraGrid.Columns.FixedStyle.Left, gdview);
                        if (i == gdview.VisibleColumns.Count - 1)
                            gdview.VisibleColumns[i].BestFit();
                        break;
                    }

                    ApplayGridFix(gdview.VisibleColumns[i].ToString(), DevExpress.XtraGrid.Columns.FixedStyle.Left, gdview);


                }
            }
            else if (info.Checked)
            {
                for (int i = gdview.VisibleColumns.Count - 1; i >= 0; i--)
                {
                    gdview.VisibleColumns[i].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.None;
                }
            }
            gdview_ColumnPositionChanged(gdview.FocusedColumn, new EventArgs());
        }
        /// <summary>
        /// 设置表格列冻结
        /// </summary>
        /// <param name="sCol"></param>
        /// <param name="fr"></param>
        private void ApplayGridFix(string sCol, DevExpress.XtraGrid.Columns.FixedStyle fr, GridView gdview)
        {
            foreach (GridColumn grCol in gdview.VisibleColumns)
            {
                if (grCol.Caption.ToString() == sCol)
                {
                    grCol.Fixed = fr;
                    return;
                }
            }
        }
        /// <summary>
        /// grid右键菜单类
        /// <creator>wangl</creator>
        /// <date>2012-02-22</date> 
        /// </summary>
        private class EASGridMenuInfo
        {
            public EASGridMenuInfo(GridColumn column, DevExpress.XtraGrid.Columns.FixedStyle style, bool check)
            {
                this.Column = column;
                this.Style = style;
                this.Checked = check;
            }
            public DevExpress.XtraGrid.Columns.FixedStyle Style;
            public GridColumn Column;
            public bool Checked;
        }
        #endregion
        
        #region 属性
        /// <summary>
        /// 最近表格布局日期
        /// </summary>
        [Category(CategoryName.Properties), Description("最近表格布局日期(如:2012-08-12),为空则表示表格布局不保存"), DefaultValue("")]
        public string LastGridLayoutDate
        {
            set;
            get;
        }
        #endregion
      
    }
}
